package com.demo.practiceui.views.animation;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

/**
 * 文字动效View
 * 核心知识点：
 * 1. LinearGradient - 线性渐变
 * 2. Shader - 着色器
 * 3. drawText - 绘制文字
 * 4. 透明度动画 - 闪烁效果
 */
public class TextEffectView extends View {

    // 文字内容
    private String text = "自定义View";
    private String subText = "Custom View Animation";

    // 画笔
    private Paint gradientTextPaint;    // 渐变文字画笔
    private Paint blinkTextPaint;       // 闪烁文字画笔
    private Paint normalTextPaint;      // 普通文字画笔

    // 尺寸
    private int width;
    private int height;

    // 渐变动画
    private float gradientOffset = 0;
    private ValueAnimator gradientAnimator;

    // 闪烁动画
    private float blinkAlpha = 1.0f;
    private ValueAnimator blinkAnimator;

    // 颜色
    private int[] gradientColors = {
            Color.parseColor("#FF5722"),
            Color.parseColor("#FFC107"),
            Color.parseColor("#4CAF50"),
            Color.parseColor("#2196F3"),
            Color.parseColor("#9C27B0")
    };

    public TextEffectView(Context context) {
        this(context, null);
    }

    public TextEffectView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextEffectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 渐变文字画笔
        gradientTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        gradientTextPaint.setTextSize(80f);
        gradientTextPaint.setTextAlign(Paint.Align.CENTER);
        gradientTextPaint.setFakeBoldText(true);

        // 闪烁文字画笔
        blinkTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        blinkTextPaint.setColor(Color.parseColor("#FF5722"));
        blinkTextPaint.setTextSize(48f);
        blinkTextPaint.setTextAlign(Paint.Align.CENTER);

        // 普通文字画笔
        normalTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        normalTextPaint.setColor(Color.parseColor("#666666"));
        normalTextPaint.setTextSize(32f);
        normalTextPaint.setTextAlign(Paint.Align.CENTER);

        startAnimations();
    }

    /**
     * 启动动画
     */
    private void startAnimations() {
        // 渐变流动动画
        gradientAnimator = ValueAnimator.ofFloat(0, 1);
        gradientAnimator.setDuration(3000);
        gradientAnimator.setRepeatCount(ValueAnimator.INFINITE);
        gradientAnimator.setInterpolator(new LinearInterpolator());
        gradientAnimator.addUpdateListener(animation -> {
            gradientOffset = (float) animation.getAnimatedValue();
            invalidate();
        });
        gradientAnimator.start();

        // 闪烁动画
        blinkAnimator = ValueAnimator.ofFloat(1.0f, 0.2f, 1.0f);
        blinkAnimator.setDuration(2000);
        blinkAnimator.setRepeatCount(ValueAnimator.INFINITE);
        blinkAnimator.addUpdateListener(animation -> {
            blinkAlpha = (float) animation.getAnimatedValue();
            invalidate();
        });
        blinkAnimator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 600;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 400;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float centerX = width / 2f;
        float y1 = height / 3f;
        float y2 = height / 2f;
        float y3 = height * 2 / 3f;

        // 1. 绘制渐变流动文字
        drawGradientText(canvas, centerX, y1);

        // 2. 绘制闪烁文字
        drawBlinkText(canvas, centerX, y2);

        // 3. 绘制说明文字
        normalTextPaint.setTextSize(28f);
        canvas.drawText("↑ 渐变流动效果", centerX, y1 + 50, normalTextPaint);
        canvas.drawText("↑ 呼吸闪烁效果", centerX, y2 + 50, normalTextPaint);
    }

    /**
     * 绘制渐变流动文字
     */
    private void drawGradientText(Canvas canvas, float x, float y) {
        // 计算渐变起点和终点（随动画移动）
        float textWidth = gradientTextPaint.measureText(text);
        float startX = x - textWidth / 2 - textWidth * gradientOffset;
        float endX = startX + textWidth * 2;

        // 创建线性渐变
        LinearGradient gradient = new LinearGradient(
                startX, y, endX, y,
                gradientColors,
                null,
                Shader.TileMode.CLAMP
        );

        gradientTextPaint.setShader(gradient);
        canvas.drawText(text, x, y, gradientTextPaint);
    }

    /**
     * 绘制闪烁文字
     */
    private void drawBlinkText(Canvas canvas, float x, float y) {
        blinkTextPaint.setAlpha((int) (255 * blinkAlpha));
        canvas.drawText("★ " + subText + " ★", x, y, blinkTextPaint);
    }

    /**
     * 设置主文字
     */
    public void setText(String text) {
        this.text = text;
        invalidate();
    }

    /**
     * 设置副文字
     */
    public void setSubText(String subText) {
        this.subText = subText;
        invalidate();
    }

    /**
     * 暂停动画
     */
    public void pause() {
        if (gradientAnimator != null && gradientAnimator.isRunning()) {
            gradientAnimator.pause();
        }
        if (blinkAnimator != null && blinkAnimator.isRunning()) {
            blinkAnimator.pause();
        }
    }

    /**
     * 恢复动画
     */
    public void resume() {
        if (gradientAnimator != null && gradientAnimator.isPaused()) {
            gradientAnimator.resume();
        }
        if (blinkAnimator != null && blinkAnimator.isPaused()) {
            blinkAnimator.resume();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (gradientAnimator != null) {
            gradientAnimator.cancel();
        }
        if (blinkAnimator != null) {
            blinkAnimator.cancel();
        }
    }
}

